package com.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.dao.UserDao;
import com.dao.UserGroupDao;
import com.dto.Pageinfo;
import com.dto.Pagers;
import com.dto.UserDto;
import com.entity.Group;
import com.entity.User;
import com.service.UserService;
import com.util.SHA1Util;
@Service("userService")
public class UserServiceImpl implements UserService{
    @Resource
    private UserDao userDao;
    @Resource
    private UserGroupDao userGroupDao;
    @Override
    public User findUser(String username) {
	// TODO Auto-generated method stub
	//System.out.println("=================");
	return userDao.finduserByName(username);
    }
    @Override
    public Pagers UserList(Pageinfo pageinfo) {
	// TODO Auto-generated method stub
	Pagers pagers=userDao.getForPage(pageinfo);
	List<User> users=(List<User>) pagers.getRows();
	List<UserDto> dtos=new ArrayList<UserDto>();
	for (User user : users) {
	    UserDto userDto=new UserDto();
	    BeanUtils.copyProperties(user, userDto,"group");
	    Group group=user.getGroup();
	    userDto.setGroupid(group.getId());
	    userDto.setGroupname(group.getGroupname());
	    dtos.add(userDto);
	}
	pagers.setRows(dtos);
	return pagers;
    }
    @Override
    public void SaveUsers(List<UserDto> dtos) {
	// TODO Auto-generated method stub
	Timestamp timestamp=new Timestamp(System.currentTimeMillis());
	for (UserDto userDto : dtos) {
	    User user=new User();
	    BeanUtils.copyProperties(userDto, user);
	    Group group=userGroupDao.findById(userDto.getGroupid());
	    user.setGroup(group);
	    user.setCreattime(timestamp);
	    user.setPassword(SHA1Util.encodeWhithKey("11111111"));
	    userDao.save(user);
	}
    }
    @Override
    public void UpdateUsers(List<UserDto> dtos) {
	// TODO Auto-generated method stub
	Timestamp timestamp=new Timestamp(System.currentTimeMillis());
	for (UserDto userDto : dtos) {
	    if(userDto.getId()<0){
		User user=new User();
		    BeanUtils.copyProperties(userDto, user);
		    Group group=userGroupDao.findById(userDto.getGroupid());
		    user.setGroup(group);
		    user.setCreattime(timestamp);
		    user.setPassword("11111111");
		    userDao.save(user);
	    }else{
		User user=userDao.findById(userDto.getId());
		BeanUtils.copyProperties(userDto, user);
		Group group=userGroupDao.findById(userDto.getGroupid());
		    user.setGroup(group);
		    user.setCreattime(timestamp);
	    }
	}
    }
    @Override
    public void DelUserIds(Integer[] ids) {
	// TODO Auto-generated method stub
	for (Integer id : ids) {
	    if(id!=1){
		userDao.DelById(id);
	    }
	}
    }
    
}
